package com.customization.assets.formmode.remind;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.customization.assets.util.*;

import com.customization.commons.LogTool;
import weaver.conn.RecordSet;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;
import weaver.system.SysRemindWorkflow;

/**
 * @author	Huangwm
 * @description	实物资台账责任人不为空时,当前所在部门与台账所在处室不匹配时,自动提示当前责任人以及资产卡片中的部门管理员（实指人员调拨-对接H4A身份调拨） 在使用
 */
public class DataDifferencesRemind extends BaseCronJob {

	private LogTool log = new LogTool("/log/assetlog/huangwm/DataDifferencesRemind",false);
	private DateTools dateTools = new DateTools();
	private DBTools dbTools = new DBTools();
	
	public String workflowid = "";
	public String getworkflowid(){
		return workflowid;
	}
	public void setworkflowid(String workflowid){
		this.workflowid = workflowid;
	}
	public String modeid = "";
	public String getmodeid(){
		return modeid;
	}
	public void setmodeid(String modeid){
		this.modeid = modeid;
	}
	public String formid = "";
	public String getformid(){
		return formid;
	}
	public void setformid(String formid){
		this.formid = formid;
	}
	public String customid = "";
	public String getcustomid(){
		return customid;
	}
	public void setcustomid(String customid){
		this.customid = customid;
	}
	public  String isNotRemind = "";
	public  String getIsNotRemind(){return isNotRemind;}
	public  void  setIsNotRemind(String isNotRemind){this.isNotRemind=isNotRemind;}

	public boolean isNotDepContent = false;//用于判断是否跨部门
	public  boolean depIsDelete = false;//用于判断原部门是否已经删除/封存

	public static void main(String[] args) throws Exception {
		GCONST.setRootPath("E:\\WEAVER9\\ecology\\");
		GCONST.setServerName("ecology");
		DataDifferencesRemind mode = new DataDifferencesRemind();
		mode.execute();
	}
	public void execute(){
		log.writeLog("实物资产数据人员数据检查开始 "+dateTools.getCurrentTimes());

		List<Map<String, String>> getAssetsInfo = getAssetsInfo();
		//先将不符台账信息中的责任人提取出来
		List<String> zrrList = getZrrList(getAssetsInfo);
		if(zrrList.size()>0){
			for(String thisZrr : zrrList){
				List<Map<String, String>> sendDatas = new ArrayList<Map<String,String>>();
				for(Map<String, String> map : getAssetsInfo){
					String zrr = map.get("zrr").toString();
					if(thisZrr.equals(zrr)){
						Map<String, String> data = new HashMap<String, String>();
						data.put("id", map.get("id"));
						data.put("kdbzc", map.get("id"));
						data.put("zcbh",  map.get("swzcbh"));
						data.put("zcmc",  map.get("zcmc"));
						data.put("dqzrr",  map.get("zrr"));
						data.put("syks",  map.get("syks"));
						data.put("dybm",  map.get("dybm"));
						data.put("subcompanyid1", map.get("subcompanyid1"));
						data.put("departmentid", map.get("departmentid"));
						data.put("lx", map.get("zclx"));
						data.put("pp", map.get("pp"));
						data.put("ggxh", map.get("ggxh"));
						data.put("dj", map.get("dj"));
						data.put("gbkph", map.get("kph"));
						sendDatas.add(data);
						/*
						rs = new RecordSet();
						String updateSql = "update uf_swzczmxx set syks="+dbTools.getDepid(thisZrr)+",dybm="+dbTools.getSubid(thisZrr)+" where id="+map.get("id");
						if(rs.execute(updateSql)){
                            log.writeLog("更新科室和部门成功  "+updateSql);
						}else {
                            log.writeLog("更新科室和部门失败  "+updateSql);
						}
						 */
					}
			}
				//sysRemind(thisZrr,sendDatas);
				//自动创建调拨单
				createSbdbFun(thisZrr,sendDatas);
			}
			//updateDybm(getAssetsInfo(),zrrList);

		}
        log.writeLog("实物资产数据人员数据检查结束 "+dateTools.getCurrentTimes());
	}

	/**
	 * 先获取到实物资产台账中存在责任人且部门数据不匹配的台账数据
	 * @return List<Map<String, String>>
	 */
	public List<Map<String, String>> getAssetsInfo(){
		List<Map<String, String>> lists = new ArrayList<Map<String, String>>();
		RecordSet rs = new RecordSet();
		//需要过滤已经发起过调拨流程的设备
		String sql = "select * from (select id,swzcbh,zcmc,zrr,dybm,(select subcompanyid1 from HrmResource where id=zrr)as subcompanyid1,zclx,pp,ggxh,dj,kph,syks," +
				"(select departmentid from HrmResource where id=zrr)as departmentid from uf_swzczmxx where zrr<>'' and zczt in(1,3) ) t where t.departmentid!=syks or dybm!=subcompanyid1 ";
        if(isNotRemind.equals("1") || isNotRemind.equals("true")){
            sql = "select * from (select id,swzcbh,zcmc,zrr,dybm,(select subcompanyid1 from HrmResource where id=zrr)as subcompanyid1,zclx,pp,ggxh,dj,kph,syks," +
					"(select departmentid from HrmResource where id=zrr)as departmentid from uf_swzczmxx where zrr<>'' and zczt in(1,3) and (yfqycdb is null or yfqycdb ='')) t where t.departmentid!=syks or dybm!=subcompanyid1 ";
        }
        rs.execute(sql);
        log.writeLog("获取到实物资产台账中存在责任人且部门数据不匹配的台账数据");
        log.writeLog(sql);
		while(rs.next()){
			Map<String, String> data = new HashMap<String, String>();
			String dybm = Util.null2String(rs.getString("dybm"));
			String syks = Util.null2String(rs.getString("syks"));
			String subcompanyid1 = Util.null2String(rs.getString("subcompanyid1"));
			String departmentid = Util.null2String(rs.getString("departmentid"));
			if(!dybm.equals(subcompanyid1)) isNotDepContent = true;//部门变更
			log.writeLog("isNotDepContent="+isNotDepContent);
			if(dbTools.getSubcomanyIsCancel(dybm).equals("1")) depIsDelete = true;//如果为1 则表示原部门已经删除了
			log.writeLog("depIsDelete="+depIsDelete);
			//if(!dybm.equals(subcompanyid1) || !syks.equals(departmentid)){
				data.put("id", rs.getString("id"));
				data.put("swzcbh", rs.getString("swzcbh"));
				data.put("zcmc", rs.getString("zcmc"));
				data.put("zrr", rs.getString("zrr"));
				data.put("dybm", dybm);
				data.put("subcompanyid1", subcompanyid1);
				data.put("subcompanyid1", departmentid);
				data.put("zclx", rs.getString("zclx"));
				data.put("pp", rs.getString("pp"));
				data.put("ggxh", rs.getString("ggxh"));
				data.put("dj", rs.getString("dj"));
				data.put("syks", rs.getString("syks"));
				data.put("kph", rs.getString("kph"));
				lists.add(data);
			//}
		}
		log.writeLog("本次获取到实物资产台账中存在责任人且部门/科室数据不匹配的台账数据"+lists.size()+"条");
		return lists;
	}

	private void updateDybm(List<Map<String, String>> getAssetsInfo,List<String> zrrList ) {
		RecordSet rs = null;
		if(zrrList.size()>0){
			for(String thisZrr : zrrList){
				for(Map<String, String> map : getAssetsInfo){
					String zrr = map.get("zrr");
					if(thisZrr.equals(zrr)){
						String id = map.get("id");
						String swzcbh = map.get("swzcbh");
						String zcmc = map.get("zcmc");
						String dybm = map.get("dybm");	
						rs = new RecordSet();
						String updateSql = "update uf_swzczmxx set syks="+dbTools.getDepid(thisZrr)+",dybm="+dbTools.getSubid(thisZrr)+" where id="+id;
						if(rs.execute(updateSql)){
                            log.writeLog("更新科室和部门成功  "+updateSql);
						}else {
                            log.writeLog("更新科室和部门失败  "+updateSql);
						}
					}
				}		
			}
		}

	}

	
	/**
	 * 获取责任人列表
	 * @param list 实物资产台账数据
	 * @return 
	 */
	public List<String> getZrrList(List<Map<String, String>> list){
		List<String> zrrList = new ArrayList<String>();
		if(list.size()>0){
			for(Map<String, String> map : list){
				String zrr = map.get("zrr");
				if(!zrrList.contains(zrr)){
					zrrList.add(zrr);
				}
			}
		}
        log.writeLog("责任人列表 "+zrrList.toString());
		return zrrList;
	}
	
	/**
	 * 获取责任人当前所在处室的部门资产管理员
	 * @param zrr
	 * @return
	 */
	public String getAssetsAdminFormZrr(String zrr){
		RecordSet rs = new RecordSet();
		String assetsAdmin = "";
		String sql = "select swzcgly from Matrixtable_1 where id=(select subcompanyid1 from HrmResource where id="+zrr+")";
		rs.execute(sql);
		while(rs.next()){
			assetsAdmin = rs.getString("swzcgly");
		}
		return assetsAdmin;
	}

	/**
	 * 获取部门所在的部门管理员
	 * @param bmid
	 * @return
	 */
	public String getAssetsAdminFormBM(String bmid){
		RecordSet rs = new RecordSet();
		String assetsAdmin = "";
		String sql = "select swzcgly from Matrixtable_1 where id="+bmid+")";
		rs.execute(sql);
		while(rs.next()){
			assetsAdmin = rs.getString("swzcgly");
		}
		return assetsAdmin;
	}

	/**
	 * 获取实物资产卡片中所在部门的部门资产管理员
	 * @param szbm
	 * @return
	 */
	public String getAsstesAdmin_sw(String szbm){

		RecordSet rs = new RecordSet();
		String assetsAdmin = "";
		String sql = "select swzcgly from Matrixtable_1 where id="+szbm;
		rs.execute(sql);
		while(rs.next()){
			assetsAdmin = rs.getString("swzcgly");
		}
		return assetsAdmin;
	}
	
	/**
	 * 发送提醒工作流
	 * @param zrr 责任人
	 * @param dataList 责任人名下的设备
	 */
	public void sysRemind(String zrr,List<Map<String, String>> dataList){
		SysRemindWorkflow sysRemindWorkflow = new SysRemindWorkflow();
		String title = "实物设备账目数据异常提醒"+dateTools.getCurrentDate();
		String assetsAdmin = getAssetsAdminFormZrr(zrr);
		String remindUsers = "".equals(assetsAdmin)?zrr:zrr+","+assetsAdmin;
		String remindContent = "";
		String asstesAdmin_sw = "";
		List<String> ids = new ArrayList<>();
		List<String> bms = new ArrayList<>();
		for(Map<String, String> map : dataList){
			String id = map.get("id");
			ids.add(id);
			String zcmc = map.get("zcmc");
			String dybm = map.get("dybm");
			if(!"".equals(dybm)){
				bms.add(dybm);
				asstesAdmin_sw = getAsstesAdmin_sw(dybm);
			}
			//正式系统
			//String link = "<br />&nbsp;" + "<a href=\"javascript:window.open('/spa/cube/index.html#/main/cube/card?type=0&modeId="+this.modeid+"&formId="+this.formid+"&billid="+id+"')\">"+zcmc+"</a>&nbsp;";
			//remindContent += link;
		}
		if(!"".equals(asstesAdmin_sw)){
			remindUsers += ","+asstesAdmin_sw;
		}
        log.writeLog("提醒人 "+remindUsers);
		//console.log(remindContent);
		try {
			//sysRemindWorkflow.setCRMSysRemind(title, 0, 1, remindUsers, dbTools.getLastname(zrr)+"您好，经检测,您当前有如下实物资产台账卡片数据中所在处室与当前个人信息中所在处室不符,请及时更新实物资产台账;"+remindContent);
			Map<String,String> mainData = new HashMap<>();
			mainData.put("xgzc", ids.toString().replace("[","").replace("]", ""));
			mainData.put("txr", "1");
			mainData.put("tzr", remindUsers);
			mainData.put("bz",dbTools.getLastname(zrr)+"您好，经检测,您当前有如下设备台账卡片数据中所在处室与当前个人信息中所在处室不符,请及时更新实物资产台账;<br /> 相关资产已自动变更为您当前所在部门！"+remindContent);
			mainData.put("xglc", "-1");
			mainData.put("xgbm", bms.toString().replace("[","").replace("]", ""));
			AssetRemind assetRemind = new AssetRemind();
			RequestService service = new RequestService();
			String requestid = service.createRequest(assetRemind.setRequestInfo("1",title,mainData));
            log.writeLog("责任人："+dbTools.getLastname(zrr)+"提醒发送成功;requestid="+requestid);
		} catch (Exception e) {
			e.printStackTrace();
            log.writeLog("发送提醒异常  "+e.getMessage());
		}
	}

	/**
	 * 创建H4A身份变更设备调拨流程
	 * @param zrr
	 * @param dataList
	 */
	public void createSbdbFun(String zrr,List<Map<String, String>> dataList){
		String title = "设备调拨申请 "+dateTools.getCurrentDate();
		Map<String,String> main = new HashMap<>();
		main.put("sqr",zrr);
		main.put("isNotDepContent", isNotDepContent?"1":"0");
		main.put("sfqbgsdb", isNotDepContent?"1":"0");
		main.put("depIsDelete", depIsDelete?"1":"0");
		title += dbTools.getLastname(zrr);
		NewCreateSbdb createSbdb = new NewCreateSbdb();
		try {
			RequestService service = new RequestService();
			String requestid = service.createRequest(createSbdb.setRequestInfo(workflowid,"1",title,main,dataList));
			log.writeLog("责任人："+dbTools.getLastname(zrr)+"调拨流程自动发成功;requestid="+requestid+" 是否跨部门："+(isNotDepContent?"1":"0")+",部门是否删除："+(depIsDelete?"1":"0"));

			if(Integer.parseInt(requestid)>10){
				//创建成功后需要更新实物表里的一个状态字段 用于标记设备已经发起过调拨了
				RecordSet rs = new RecordSet();
				String updateSql = "update uf_swzczmxx set yfqycdb=1 where zrr="+zrr;
				log.writeLog(updateSql);
				if(rs.execute(updateSql)){
					log.writeLog("自动发起调拨流程后更新标记成功");
				}else {
					log.writeLog("自动发起调拨流程后更新标记失败");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.writeLog("责任人："+dbTools.getLastname(zrr)+"调拨流程自动发失败;");
		}
	}

}
